package cn.mxz.generator.config;

import java.util.ArrayList;
import java.util.List;

public class MethodImpl implements IMethod {

	private IReturn returnData;

	private String name;

	private List<IField> args;

	private long id;

	private String methodDoc;

	private List<MethodBack> backs;

	private GeneratorConfig config;

	public MethodImpl(
			String methodText, 
			String methodDoc, 
			String returnDoc,
			List<String> argsDoc,
			List<String> backs, 
			long id,
			GeneratorConfig config
			) {

		this.config = config;
		returnData = buildReturn(methodText, returnDoc);
		name = buildName(methodText);
		args = buildArgs(methodText, argsDoc);
		
		this.backs = buildBacks(backs);
		
		this.id = id;
		this.setMethodDoc(methodDoc);
	}

	public List<MethodBack> buildBacks(List<String> b) {
		List<MethodBack> mbs = new ArrayList<MethodBack>();
		for (String s : b) {
			mbs.add(new MethodBackImpl(s, config));
		}
		return mbs;
	}

	@Override
	public String toString() {
		return name;
	}
	
	private List<IField> buildArgs(String methodText, List<String> argsDoc) {

		List<IField> all = new ArrayList<IField>();
		String fileds = methodText.replaceAll(".*\\(", "").replaceAll("\\)", "");
		
		String[] split;
		if(fileds.isEmpty()) {
			split = new String[0];
		} else {
			split = fileds.split(",");
		}
		
		checkArgsCount(split, argsDoc, methodText);
		
		for (int i = 0; i < split.length; i++) {
			String filed = split[i].trim();
			IField f = new FieldImpl();
			
			String[] s = filed.split(" ");
			f.setType(s[0]);
			f.setDoc(argsDoc.get(i));
			f.setName(s[1]);
			all.add(f);
		}
		
		return all;
	}

	private void checkArgsCount(String[] split, List<String> argsDoc, String methodText) {
		if(split.length != argsDoc.size()) {
			throw new RuntimeException("参数数量和<args>数量不匹配!" + split.length + ", " + argsDoc.size() + ", " + methodText);
		}
	}

	private String buildName(String methodText) {
		return methodText.replaceAll("\\(.*\\)", "").replaceAll(".* ", "");
	}

	private IReturn buildReturn(String methodText, String returnDoc) {
		IReturn returnData = new ReturnImpl();
		String[] split = methodText.split(" ");
		returnData.setKeyWord(split[0]);
		returnData.setReturnDoc(returnDoc);
		return returnData;
	}

	@Override
	public long getId() {
		return id;
	}

	@Override
	public List<IField> getArgs() {
		return args;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public IReturn getReturn() {
		return returnData;
	}

	@Override
	public String getMethodDoc() {
		return methodDoc;
	}

	private void setMethodDoc(String methodDoc) {
		this.methodDoc = methodDoc;
	}

	@Override
	public List<MethodBack> getBacks() {
		return backs;
	}

}
